﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace myTravian
{

    public partial class traBrowser : UserControl
    {

            
        /// <summary>
        /// 取回目前的結果，如果有發生錯誤時。
        /// </summary>
        [Category("Travian")]
        [Description("取回目前的結果，如果有發生錯誤時。把錯誤留下來")]
        public string Message
        {
            get { return message; }
        }

        /// <summary>
        /// 當Browse 忙錄時時間要停留多久要重試
        /// </summary>
        //[Category("Travian")]
        //[Description("當Browse 忙錄時時間要停留多久要重試")]
        //public int WaitSecond
        //{
        //    set
        //    {
        //        waitSecond = value;
        //    }
        //    get
        //    {
        //        return waitSecond;
        //    }
        //}
        //protected int waitSecond = 2;

        protected string message = "";
        protected HtmlDocument doc = null;
        protected MSHTML.IHTMLDocument3 dom = null;
        public int itest = 0;

        public traBrowser()
        {
            InitializeComponent();
            webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
        }

        void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            itest++;
            doc = webBrowser1.Document;
            //dom = webBrowser1.Document.DomDocument as MSHTML.IHTMLDocument3;
        }

        public void browserIsReadey()
        {
            while (true)
            {
                System.Threading.Thread.Sleep(1000);
                Application.DoEvents();
                if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
                {
                    break;
                }
            }
            //while (webBrowser1.IsBusy || string.IsNullOrEmpty(webBrowser1.StatusText))
            //{
            //    System.Threading.Thread.Sleep(1000);
            //    Application.DoEvents();
            //}
            //int x = 0;
            //while (true)
            //{
            //    System.Threading.Thread.Sleep(2000);
            //    Application.DoEvents();
            //    if( (x == 2) || (webBrowser1.ReadyState == WebBrowserReadyState.Complete))
            //    {
            //        break;
            //    }
            //    x++;
            //}
        }

        /// <summary>
        /// 所有要取HtmlDocument 都要從這取，以確定Browser 已經結束
        /// </summary>
        /// <returns></returns>
        public HtmlDocument GetHtmlDocument()
        {
            browserIsReadey();
            return doc;
        }

        /// <summary>
        /// 執行網址路徑
        /// </summary>
        /// <param name="address"></param>
        public void NavigateURL(string address)
        {
            if (String.IsNullOrEmpty(address))
            {
                message = "沒有給網址路徑!";
            }
            if (address.Equals("about:blank")) return;
            if (!address.StartsWith("http://") &&
                !address.StartsWith("https://"))
            {
                address = "http://" + address;
            }
            try
            {
                webBrowser1.Navigate(new Uri(address));
                browserIsReadey();
            }
            catch (System.UriFormatException ex)
            {
                message = ex.Message;
            }
        }

        public HtmlElement GetElementByID(string id)
        {
            browserIsReadey();
            return doc.GetElementById(id);            
        }

        //public MSHTML.IHTMLElement getElementById(string id)
        //{
        //    browserIsReadey();            
        //    return dom.getElementById(id);
        //}

        /// <summary>
        /// 依條件所傳回的集合
        /// </summary>
        /// <param name="elementTagName">EX:input、a HTML的 TAG</param>
        /// <param name="attributeName">EX:name、alt HTML中TAG的屬性</param>
        /// <param name="attributeValues">對應到HTML中TAG的屬性值</param>
        /// <returns></returns>
        public System.Collections.ArrayList GetElementByName(string elementTagName, string attributeName,string[] attributeValues)
        {
            browserIsReadey();
            System.Collections.ArrayList xy = new System.Collections.ArrayList();   
            foreach (HtmlElement input in doc.GetElementsByTagName(elementTagName))
            {
                foreach (string attributeValue in attributeValues)
                {
                    if (input.GetAttribute(attributeName).ToLower().Equals(attributeValue))
                    {
                        xy.Add(input);
                    }
                }
            }
            return xy;
        }

        /// <summary>
        /// 取回軍隊
        /// </summary>
        /// <returns></returns>
        public DataTable GetTroops()
        {
            browserIsReadey();
            DataTable dt = new DataTable();
            string[] columnNames = { "troops", "input", "count" };
            for (int i = 0; i < columnNames.Length; i++)
            {
                dt.Columns.Add(columnNames[i]);
            }
            HtmlElement td = this.doc.GetElementById("troops");
            HtmlElementCollection troops = td.GetElementsByTagName("td");
            try
            {
                foreach (HtmlElement troop in troops)
                {
                    HtmlElementCollection soldier_img = troop.GetElementsByTagName("img");
                    HtmlElementCollection soldier_text = troop.GetElementsByTagName("input");
                    HtmlElementCollection soldier_a = troop.GetElementsByTagName("a");
                    DataRow row = null;
                    if (soldier_img.Count > 0 & soldier_text.Count > 0)
                    {
                        row = dt.NewRow();
                        row[columnNames[0]] = soldier_img[0].GetAttribute("title").ToString();
                        row[columnNames[1]] = soldier_text[0].GetAttribute("name").ToString();
                        if (soldier_a.Count == 0)
                        {
                            row[columnNames[2]] = "0";
                        }
                        else
                        {
                            row[columnNames[2]] = soldier_a[0].InnerText.Replace("(", "").Replace(")", ""); 
                        }                        
                        dt.Rows.Add(row);
                    }
                }
                if (dt.Rows.Count == 0)
                {
                    message = "無法取回軍隊資料！";
                }
            }
            catch (System.Exception ex)
            {
                message = ex.Message;
            }
            return dt;
        }

        public string GetBrowseState()
        {
            return webBrowser1.StatusText;
        }

        public void ElementInvok(HtmlElement html, string invokeMethod)
        {
             //webBrowser1.Document.DomDocument
            
            //html.RaiseEvent("onclick");
            html.InvokeMember(invokeMethod);
            browserIsReadey();
           
                        
        }

        public string GetCurrentURL()
        {
            return webBrowser1.Url.ToString();
        }
    }
}
